from rest_framework import serializers
from django_redis import get_redis_connection

from goods.models import SKU
from user.models import User


class CartsSerializers(serializers.ModelSerializer):

    sku_id = serializers.IntegerField(min_value=1,label='sku_id',required=False)
    count = serializers.IntegerField(min_value=1,label='数量',required=False)
    selected = serializers.BooleanField(label='是否勾选',default=True,required=False)

    class Meta:
        model = SKU
        fields = '__all__'
        extra_kwargs = {
            'caption': {'required': False},
            'price': {'required':False},
            'market_price' : {'required':False},
            'name' : {'required':False},
            'cost_price' : {'required':False},
            'category' : {'required':False},
            'goods' : {'required':False},
        }

    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs



class CartsdelSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1,label='sku_id')

    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

class CartsSelectSerializers(serializers.Serializer):
    selected = serializers.BooleanField(label='是否选中')


